﻿using System;
using System.Collections.Generic;
using System.Dynamic;

namespace BusinessLayer
{
    /// <summary>
    /// The business entity.
    /// </summary>
    public abstract class BusinessEntity
    {

        /// <summary>
        /// The properties.
        /// </summary>
        protected Dictionary<string, object> properties;

        /// <summary>
        /// Initialize the object.
        /// </summary>
        internal void Initialize(Dictionary<string, object> entity)
        {
            this.properties = entity;
        }

        /// <summary>
        /// Convert BL entity to DAL entity.
        /// </summary>
        internal static Dictionary<string, object> ToDalEntity(BusinessEntity entity)
        {
            return entity.properties;
        }

        /// <summary>
        /// Gets the property.
        /// </summary>
        /// <exception cref="MissingFieldException">
        /// </exception>
        protected object Get(string prop)
        {
            if (this.properties.ContainsKey(prop))
                return this.properties[prop];
            else
                throw new MissingFieldException("Missing field " + prop);
        }

        /// <summary>
        /// Sets the property.
        /// </summary>
        /// <exception cref="MissingFieldException">
        /// </exception>
        protected void Set(string prop, object value)
        {
            if (this.properties.ContainsKey(prop))
                this.properties[prop] = value;
            else
                throw new MissingFieldException("Missing field " + prop);
        }

        /// <summary>
        /// Save the entity.
        /// </summary>
        public abstract void Save();

        public override string ToString()
        {
            string s = "";
            foreach (var pair in properties)
            {
                s += pair.Key + " = " + pair.Value.ToString() + "; ";
            }
            return s;
        }
    }
}
